import xbmc
import xbmcgui
import os
import sys
import urllib, re,urllib2
import time




BASE_RESOURCE_PATH = os.path.join( os.getcwd().replace( ";", "" ), "resources" )
sys.path.append( os.path.join( BASE_RESOURCE_PATH, "lib" ) )
import language
import feedparser

__language__ = language.Language().localized
_ = sys.modules[ "__main__" ].__language__

KEY_REMOTE_BACK = 216
KEY_REMOTE_MENU = 247
KEY_REMOTE_INFO = 195
KEY_BUTTON_R_TRIGGER = 263
KEY_BUTTON_BACK = 275
KEY_KEYBOARD_ESC = 61467
KEY_KEYBOARD_I    =  61513
KEY_KEYBOARD_M    =  61517

__title__ = _(0)
__scriptname__ = "EasyNews Streamer"
__version__ = "1.1"

url1 = "/global4/search.html?gps=unrar+"
url2 = "&sbj=&from=&ns=&fil=&fex=&vc=&ac=&fty^5B^5D=MOVIE&s1=nrfile&s1d=^2B&s2=nrfile&s2d=^2B&s3=dsize&s3d=^2B&pby="
url3 = "&pno=1&sS=0&grpF^5B^5D="
url4 = "&u=1&plain=1&svL=&d1=&d1t=&d2=&d2t=&b1=&b1t=14&b2=&b2t=&px1=&px1t=&px2=&px2t=&fps1=&fps1t=&fps2=&fps2t=&bps1=&bps1t=&bps2=&bps2t=&hz1=&hz1t=&hz2=&hz2t=&rn1=&rn1t=&rn2=&rn2t=&hf=1&fly=2&pno=1&sS=5"

url_all3 ="&pno=1&sS=5&u=1&svL=&d1=&d1t=&d2=&d2t=&b1=&b1t=14&b2=&b2t=&px1=&px1t=&px2=&px2t=&fps1=&fps1t=&fps2=&fps2t=&bps1=&bps1t=&bps2=&bps2t=&hz1=&hz1t=&hz2=&hz2t=&rn1=&rn1t=&rn2=&rn2t=&fly=2"

scriptPath = os.getcwd().replace(';','')
BASE_SETTINGS_PATH = os.path.join( "P:\\script_data", __scriptname__ )

dialogProgress = xbmcgui.DialogProgress()

############################################################

class WindowXMLAboutDialog(xbmcgui.WindowXMLDialog):
    def __init__(self,strXMLname, strFallbackPath):
        self.heading = ""
        self.line1 = ""
        self.line2 = ""
        self.line3 = ""

    def onInit(self):
        print "ABOUT DIAG onInit(): Window Initalized"
        self._setLines()

    def onAction(self, action):
        buttonCode =  action.getButtonCode()
        actionID   =  action.getId()
        print "ABOUT DIAG: onAction(): actionID=%i buttonCode=%i" % (actionID,buttonCode)
        if (buttonCode == KEY_BUTTON_BACK or buttonCode == KEY_KEYBOARD_ESC or buttonCode == 61467):
            self.close()

    def onClick(self, controlID):
        """
            onClick(self, controlID) is the replacement for onControl. It gives an interger.
            This function has been implemented and works
        """
        print "ABOUT DIAG: onclick(): control %i" % controlID
        if (controlID == 10):
            xbmc.sleep(5)
            self.close()

    def onFocus(self, controlID):
        """"
            onFocus(self, int controlID)
            This function has been implemented and works
        """
        print "ABOUT DIAG onFocus(): control %i" % controlID

    def _setLines(self):
        self.getControl(1).setLabel(self.heading)
        self.getControl(2).setLabel(self.line1)
        self.getControl(3).setLabel(self.line2)
        self.getControl(4).setLabel(self.line3)

    def setHeading(self, heading):
        self.heading = heading

    def setLines(self, line1,line2, line3):
        self.line1 = line1
        self.line2 = line2
        self.line3 = line3

############################################################
class Settings:

    def get_settings( self ):
        """ read settings from a settings.txt file in BASE_SETTINGS_PATH """
        try:
            settings_file = open( os.path.join( BASE_SETTINGS_PATH, "settings.txt" ), "r" )
            settings = eval( settings_file.read() )
            settings_file.close()
        except:
            settings = self._use_defaults()
        return settings

    def _use_defaults( self, show_dialog=False ):
        """ setup default values if none obtained """
        settings = {
            "username": "john_doe",
            "password": "1234",
            "port": "80",
            }
        return settings

    def save_settings( self, settings ):
        """ save settings to a settings.txt file in BASE_SETTINGS_PATH """
        try:
            print "save_settings"
            if ( not os.path.isdir( BASE_SETTINGS_PATH ) ):
               os.makedirs( BASE_SETTINGS_PATH )
            print "Saving to %s" % (BASE_SETTINGS_PATH)   
            settings_file = open( os.path.join( BASE_SETTINGS_PATH, "settings.txt" ), "w" )
            settings_file.write( repr( settings ) )
            settings_file.close()
            return True
        except:
            return False

############################################################

class WindowXMLSettingsDialog( xbmcgui.WindowXMLDialog ):
    def __init__( self, *args, **kwargs ):
        pass

    def onInit( self ):
        print "Got Settings Dialog onInit"
        self._get_settings()
        self._set_labels()
        self._set_functions()
        self._set_controls_values()

    def onClick( self, controlId ):
        self.functions[ controlId ]()

    def onFocus( self, controlId ):
        self.controlId = controlId

    def onAction( self, action ):
        buttonCode =  action.getButtonCode()
        actionID   =  action.getId()
        if (buttonCode == KEY_BUTTON_BACK or buttonCode == KEY_REMOTE_BACK or buttonCode == KEY_KEYBOARD_ESC or buttonCode == 61467):
            self._close_dialog()

    def _get_settings( self ):
        self.settings = Settings().get_settings()

    def _set_labels( self ):
        xbmcgui.lock()
        try:
            self.getControl( 20 ).setLabel( __scriptname__ )
            self.getControl( 30 ).setLabel( "%s: %s" % ( _( 1006 ), __version__, ) )
            self.getControl( 250 ).setLabel( _( 250 ) )
            self.getControl( 251 ).setLabel( _( 251 ) )

            
            self.getControl( 201 ).setLabel( _( 201 ) )
            self.getControl( 202 ).setLabel( _( 202 ) )
            self.getControl( 203 ).setLabel( _( 203 ) )
        except: pass
        xbmcgui.unlock()

    def _set_functions( self ):
        self.functions = {}
        self.functions[ 250 ] = self._save_settings
        self.functions[ 251 ] = self._close_dialog
        self.functions[ 201 ] = self._change_setting1
        self.functions[ 202 ] = self._change_setting2
        self.functions[ 203 ] = self._change_setting3


    def _set_controls_values( self ):
        xbmcgui.lock()
        try:
            self.getControl( 221 ).setLabel( self.settings[ "username" ] )
            self.getControl( 222 ).setLabel( self.settings[ "password" ] )
            self.getControl( 223 ).setLabel( self.settings[ "port" ] )
        except: pass
        xbmcgui.unlock()

    def _change_setting1( self ):
        keyboard = xbmc.Keyboard("")
	keyboard.doModal()
	if (keyboard.isConfirmed()):
	    self.settings[ "username" ] = keyboard.getText()
        self._set_controls_values()

    def _change_setting2( self ):
        keyboard = xbmc.Keyboard("")
	keyboard.doModal()
	if (keyboard.isConfirmed()):
	    self.settings[ "password" ] = keyboard.getText()
        self._set_controls_values()

    def _change_setting3( self ):
        keyboard = xbmc.Keyboard("")
	keyboard.doModal()
	if (keyboard.isConfirmed()):
	    self.settings[ "port" ] = keyboard.getText()
        self._set_controls_values()
    
    def _save_settings( self ):
        ok = Settings().save_settings( self.settings )
        if ( not ok ):
            ok = xbmcgui.Dialog().ok( __scriptname__, _( 230 ) )
        self._close_dialog()   
     
    def _close_dialog( self ):
        xbmc.sleep(5)
        self.close()


            
##################################################################
class WindowXMLSearchDialog( xbmcgui.WindowXMLDialog ):
    def __init__( self, *args, **kwargs ):
        pass

    def onInit( self ):
        print "Got Search Dialog onInit"
        self._get_defaults()
        self._set_labels()
        self._set_functions()
        self._set_controls_values()
        self.searched = 0;

    def onClick( self, controlId ):
        self.functions[ controlId ]()

    def onFocus( self, controlId ):
        self.controlId = controlId

    def onAction( self, action ):
        buttonCode =  action.getButtonCode()
        actionID   =  action.getId()
        if (buttonCode == KEY_BUTTON_BACK or buttonCode == KEY_REMOTE_BACK or buttonCode == KEY_KEYBOARD_ESC or buttonCode == 61467):
            self._close_dialog()

    def get_search_string( self ):
        #if selected group is "All"
        if (self.group_choices[self.group_offset] == _( 2066 )):
           return "%s%s%s%s%s" % ( url1, self.search_term.replace(' ','+'),  url2, self.max_results_choices[self.max_results_offset],  url_all3,)
        else:
           return "%s%s%s%s%s%s%s" % ( url1, self.search_term.replace(' ','+'),  url2, self.max_results_choices[self.max_results_offset],  url3 ,self.group_choices[self.group_offset], url4,)


    def _get_defaults( self ):
        print "_get_defaults"
        self.search_term = ""
        self.max_results_offset = 0
        self.max_results_choices = ( _( 2050 ), _( 2051 ), _( 2052 ),_( 2053 ),)
        self.group_offset = 0
        self.group_choices = ( _( 2066 ), _( 2060 ), _( 2061 ), _( 2062 ),_( 2063 ),_( 2064 ),_( 2065 ),)

    def _set_labels( self ):
        xbmcgui.lock()
        try:
            self.getControl( 20 ).setLabel( __scriptname__ )
            self.getControl( 30 ).setLabel( "%s: %s" % ( _( 1006 ), __version__, ) )
            self.getControl( 252 ).setLabel( _( 252 ) )
            self.getControl( 251 ).setLabel( _( 251 ) )

            
            self.getControl( 204 ).setLabel( _( 204 ) )
            self.getControl( 205 ).setLabel( _( 205 ) )
            self.getControl( 206 ).setLabel( _( 206 ) )
        except: pass
        xbmcgui.unlock()

    def _set_functions( self ):
        self.functions = {}
        self.functions[ 252 ] = self._search
        self.functions[ 251 ] = self._close_dialog
        self.functions[ 204 ] = self._change_param1
        self.functions[ 205 ] = self._change_param2
        self.functions[ 206 ] = self._change_param3


    def _set_controls_values( self ):
        xbmcgui.lock()
        try:
            self.getControl( 224 ).setLabel(self.search_term)
            self.getControl( 225 ).setLabel(self.max_results_choices[self.max_results_offset])
            self.getControl( 226 ).setLabel(self.group_choices[self.group_offset])
        except: pass
        xbmcgui.unlock()

    def _change_param1( self ):
        keyboard = xbmc.Keyboard(self.search_term)
	keyboard.doModal()
	if (keyboard.isConfirmed()):
	    self.search_term = keyboard.getText()
        self._set_controls_values()

    def _change_param2( self ):
        if (self.max_results_offset < 4):
           self.max_results_offset+=1
        else:
           self.max_results_offset = 0
        print self.max_results_offset
        self._set_controls_values()

    def _change_param3( self ):
        if (self.group_offset < 7):
           self.group_offset+=1
        else:
           self.group_offset = 0
        self._set_controls_values()
    
    def _search( self ):
        self.searched = 1
        self._close_dialog()   
     
    def _close_dialog( self ):
        xbmc.sleep(5)
        self.close()
        
##################################################################        

class EasyNewsStreamerWindowXML(xbmcgui.WindowXML):
    def __init__(self,strXMLname, strFallbackPath,strDefaultName,bforeFallback=0):
        if os.path.isfile(os.path.join( BASE_SETTINGS_PATH, "search.xml")) == True:
          self.d = feedparser.parse(os.path.join( BASE_SETTINGS_PATH, "search.xml"))
        
        self.t0 = 0
        self.t1 = 0
        self.speed_counter = 0
        self.rate = 0
        self.cancel_download = 0

    def onInit(self):
        self.settings = Settings().get_settings()
 
        self.search_title = self.getControl(101)
 
        if os.path.isfile(os.path.join( BASE_SETTINGS_PATH, "search.xml")) == True:     
          self.fill_list()
        else:
          self.search_title.setLabel(_(103)) #no previous search
        
        if os.path.isfile(os.path.join( BASE_SETTINGS_PATH, "settings.txt")) == False:
          self.launch_settings()
           
        

    def onAction(self, action):
        buttonCode =  action.getButtonCode()
        actionID   =  action.getId()
        print "MAIN onAction(): actionID=%i buttonCode=%i" % (actionID,buttonCode)
        if (buttonCode == KEY_BUTTON_BACK or buttonCode == KEY_KEYBOARD_ESC or buttonCode == KEY_REMOTE_BACK):
            self.close()
        elif (buttonCode == KEY_KEYBOARD_I or buttonCode == KEY_REMOTE_INFO or buttonCode == KEY_BUTTON_R_TRIGGER ):
            print "Info was pressed"
            selItem = self.getListItem(self.getCurrentListPosition())
	    if (selItem.getLabel2() != "retry"):
	       
	       #download the thumbnail and display it	       
               if (self.get_thumb_url() != "fail"):
                  head = "http://" + self.settings["username"] +':' + self.settings["password"] +'@'
		  print self.get_thumb_url().replace('http://', head)
		  
	          self.downloadDialog = xbmcgui.DialogProgress()
	          self.downloadDialog.create("Getting Thumbnail...")
		  loc = urllib.URLopener()
	     
                  loc.retrieve(self.get_thumb_url().replace('http://', head), os.path.join( BASE_SETTINGS_PATH, "thumb.jpg"))
                  self.downloadDialog.close()

	          dialog = ImageViewerClass()
	          dialog.doModal()
                  del dialog
                  
        elif (buttonCode == KEY_KEYBOARD_M or buttonCode == KEY_REMOTE_MENU):
            print "Menu Was Pressed"
            try:
               dialog = xbmcgui.Dialog()
	       if dialog.yesno(_(0), _(101)):
                  dialog2 = xbmcgui.Dialog()
	          self.fn = dialog.browse(3, _(102), 'files')
	          
	          selItem = self.getListItem(self.getCurrentListPosition())
                  
                  name = selItem.getLabel2()
                  name = name[name.rfind("/")+1:]
                  name = name.replace('%20','_')
                  name = name.replace('%28','(')
                  self.name = name.replace('%29',')')
                  self.save(selItem.getLabel2(), self.fn+self.name, self.name)
	    except Exception, e:
	          print e
	          
	    

    def onClick(self, controlID):
        """
            onClick(self, controlID) is the replacement for onControl. It gives an interger.
            This function has been implemented and works
        """
        print "MAIN onclick(): control %i" % controlID
        
        #About Dialog Selected
        if (controlID == 7):
            dialog = WindowXMLAboutDialog("DialogOK.xml",os.path.join(scriptPath,'DefaultSkin'))
            dialog.setHeading(__title__ + ": About")
            dialog.setLines("EasyNews Streamer v 1.1","Coded by Bortoni with forum help by Nuka1195","www.bortoni.com")
            dialog.doModal()
            del dialog
            
            
            

        #New Search Dialog Selected
        elif (controlID == 13):
            print "Search Selected"
	    self.launch_search()
                       
            
        #Settings Selected    
        elif (controlID == 99):
            print "Settings Selected"
            self.launch_settings()
                
        #Search Item Selected        
        elif (50 <= controlID <= 59):
            print "CurrentListPosition: %i" % self.getCurrentListPosition()
            selItem = self.getListItem(self.getCurrentListPosition())
            if (selItem != -1):
               print selItem.getLabel2()
               if(selItem.getLabel2() == "retry"):
                  self.launch_search()
               else:
                  xbmc.Player().play(selItem.getLabel2())
                  xbmc.sleep(5)
                  self.close()
            
    def onFocus(self, controlID):
        print "MAIN onFocus(): control %i" % controlID
        if (controlID == 50):
            print ' MAIN The control with id="5" just got focus'
            
    def fill_list(self):
        print "In ur listz adding items"
        temp_str = self.d.feed.title.replace(' Easynews Global4 v0.1','')
	temp_str2 = temp_str.replace('-','')
        self.search_title.setLabel("Search: %s" % (temp_str2.replace('unrar ','')))
        self.clearList()
        head = "http://" + self.settings["username"] +':' + self.settings["password"] +'@'
        tail = "easynews.com:" + self.settings["port"] 
        if (len(self.d.entries) == 0):
           self.addItem(xbmcgui.ListItem("No Results", "retry", "defaultVideo.png", "defaultVideoBig.png"))
        else:   
           for x in range( 0, len(self.d.entries) ):
	      temp_str = self.d.entries[x].title.replace('yEnc','')
	      title_str = temp_str.replace('AutoUnRAR','')
	      link_str = self.d.entries[x].link.replace('http://', head)
	      self.addItem(xbmcgui.ListItem(title_str, link_str.replace('easynews.com', tail), "defaultVideo.png", "defaultVideoBig.png"))

    def launch_search(self):
        dialog = WindowXMLSearchDialog("EasyNewsStreamerSearch.xml",scriptPath,"DefaultSkin")
	dialog.doModal()
	if (dialog.searched == 1):
	    self.clearList()
	    self.search_title.setLabel(_(104)) #searching
	    temp_string = "http://%s:%s@members.easynews.com%s" % (self.settings["username"], self.settings["password"], dialog.get_search_string())
	    self.search_string = temp_string.replace('^','%')
	    self.downloadDialog = xbmcgui.DialogProgress()
	    self.downloadDialog.create("Searching...")
	    sock = urllib.urlopen(self.search_string)
	    htmlSource = sock.read()
	    sock.close()
	    html_file = open( os.path.join( BASE_SETTINGS_PATH, "search.xml" ), "w" )
	    html_file.write( htmlSource )
	    html_file.close()
	    print "file is closed"
	    self.d = feedparser.parse(os.path.join( BASE_SETTINGS_PATH, "search.xml"))
	    print "file is parsed"
	    self.fill_list()
	    self.downloadDialog.close()
	    xbmc.sleep(5)               
        del dialog
    
    def launch_settings(self):
        dialog = WindowXMLSettingsDialog("EasyNewsStreamerSettings.xml",scriptPath,"DefaultSkin")
	dialog.doModal()
	self.settings = Settings().get_settings()
        del dialog   

    def get_thumb_url(self):
        item = self.getCurrentListPosition()
        print item
        raw_link = self.d.entries[item].link
        print raw_link
        temp_link = raw_link[0:49] + 'th-' + raw_link[49:]

        if (temp_link.find('.avi') != -1):
            return temp_link.replace('.avi', '.jpg')
        elif (temp_link.find('.mkv') != -1):
            return temp_link.replace('.mkv', '.jpg')        
        elif (temp_link.find('.wmv') != -1):
            return temp_link.replace('.wmv', '.jpg')        
        elif (temp_link.find('.mov') != -1):
            return temp_link.replace('.mov', '.jpg')        
        elif (temp_link.find('.mp4') != -1):
            return temp_link.replace('.mp4', '.jpg')
        elif (temp_link.find('.mpg') != -1):
            return temp_link.replace('.mpg', '.jpg')
        elif (temp_link.find('.asf') != -1):
            return temp_link.replace('.asf', '.jpg')     
        return "fail"    




    def save(self,url,destination,name):
	self.downloadDialog = xbmcgui.DialogProgress()
	self.downloadDialog.create(_(105),_(106)+name+_(107), destination, " ")
	try:
	        self.t0 = time.clock()
		DL=urllib.urlretrieve( url , destination , self.hook)
		self.downloadDialog.close()
	except Exception,e:
		self.downloadDialog.close()
		dialog = xbmcgui.Dialog()


    def hook(self,count_blocks, block_size, total_size):
        
        if self.speed_counter == 40:
           self.t1 = time.clock()
           self.rate = ((block_size*40) / 1024)//(self.t1 - self.t0)
           self.t0 = self.t1
           self.speed_counter = 0
        else:
           self.speed_counter = self.speed_counter + 1
           
        current_size = block_size * count_blocks
	value = current_size * 100 / total_size
	temp_str = str(self.rate) + " Kb/s"
	self.downloadDialog.update(value, "Downloading "+self.name+" to:", self.fn, temp_str )
	if self.downloadDialog.iscanceled():
	   raise
		
		


############################################################

class ImageViewerClass(xbmcgui.WindowDialog):
  def __init__(self):
    self.scaleX = ( float(self.getWidth())  / float(1280) )
    self.scaleY = ( float(self.getHeight()) / float(720) )
    self.addControl(xbmcgui.ControlImage(0, 0, int(1280 * self.scaleX), int(720 * self.scaleY), os.path.join( BASE_SETTINGS_PATH, "thumb.jpg"), aspectRatio=2))
 
  def onAction(self, action):
    buttonCode =  action.getButtonCode()
    actionID   =  action.getId()
    if (buttonCode == KEY_BUTTON_R_TRIGGER or buttonCode == KEY_KEYBOARD_I or buttonCode == KEY_REMOTE_INFO or buttonCode == KEY_BUTTON_BACK or buttonCode == KEY_KEYBOARD_ESC or buttonCode == KEY_REMOTE_BACK or buttonCode == KEY_REMOTE_MENU or buttonCode == 61467):
       self.close()

############################################################

if __name__ == '__main__':
    w = EasyNewsStreamerWindowXML("EasyNewsStreamer.xml",scriptPath,"DefaultSkin")
    w.doModal()
    del w
    